package com.rdxer.service;

import com.rdxer.dataview.AnswerSheetDV;
import com.rdxer.dataview.PaperGradeDV;
import com.rdxer.model.Account;
import com.rdxer.model.AnswerSheet;
import com.rdxer.model.Paper;
import com.rdxer.repository.PaperRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GradeService {
    @Autowired
    private PaperRepository paperRepository;
    @Autowired
    private AnswerSheetService answerSheetService;
    @Autowired
    private AccountService accountService;

    public List<Paper> findAllPaperByUserId(String userId) {

        List<Paper> allByUserId = paperRepository.findAllByUserId(userId);

        return allByUserId;
    }

    public List<PaperGradeDV> findAllPaperGradeDVByUserId(String id) {
        List<Paper> list = findAllPaperByUserId(id);
        List<PaperGradeDV> listDV = new ArrayList<>();
        for (Paper paper : list) {
            PaperGradeDV dv = new PaperGradeDV();
            dv.setPaper(paper);
            List<AnswerSheet> byPaper = answerSheetService.findAllByPaper(paper.getId());
            int count = byPaper.size();
            dv.setCount((long) count);
            long toReadCount = byPaper.stream().filter(v -> !v.getResolve()).count();
            dv.setToReadCount(toReadCount);
            listDV.add(dv);
        }
        return listDV;
    }
    public List<AnswerSheet> getAnswerSheetListByPaper(String paperId) {
        List<AnswerSheet> allByPaper = answerSheetService.findAllByPaper(paperId);
        return allByPaper;
    }

    public List<AnswerSheetDV> getAnswerSheetDVListByPaper(String paperId) {
        List<AnswerSheet> list = getAnswerSheetListByPaper(paperId);
        List<AnswerSheetDV> rs = new ArrayList<>();

        for (AnswerSheet sheet : list) {
            AnswerSheetDV r = new AnswerSheetDV();
            BeanUtils.copyProperties(sheet,r);
            Account account = accountService.show(sheet.getUserId());
            r.setAccount(account);
            rs.add(r);
        }

        return rs;
    }

    public PaperGradeDV findPaper(String paperId) {

        Paper paper = paperRepository.findById(paperId).get();

        PaperGradeDV dv = new PaperGradeDV();
        dv.setPaper(paper);
        List<AnswerSheet> byPaper = answerSheetService.findAllByPaper(paper.getId());
        int count = byPaper.size();
        dv.setCount((long) count);
        long toReadCount = byPaper.stream().filter(v -> !v.getResolve()).count();
        dv.setToReadCount(toReadCount);

        return dv;
    }
}
